// pages/search/search.js
import request from '../../utils/request.js'
let isSend = false
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		placeholderContent: '',
		hotList: [],
		searchContent: '',
		searchList: [],
		historyList: [],
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		this.getInitData()
	},

	async getInitData() {
		let res = await request('/search/default')
		let hotList = await request('/search/hot/detail')
		this.setData({
			placeholderContent: res.data.showKeyword,
			hotList: hotList.data
		})
	},
	
	getSearchHistory() {
		let historyList = wx.getStorageSync('searchHistory')
		if (historyList) {
			this.setData({
				historyList
			})
		}
	},

	handleInputChange(e) {
		this.setData({
			searchContent: e.detail.value.trim()
		})
		if (isSend) {
			return
		}
		this.getSearchList()
		isSend = true
		setTimeout(async () => {
			isSend = false
		}, 300)

	},
	
	async getSearchList() {
		if (!this.data.searchContent) {
			this.setData({
				searchList: []
			})
			return
		}
		let {searchContent,historyList} = this.data
		let res = await request('/search', {
			keywords: this.data.searchContent,
			limit: 10
		})
		this.setData({
			searchList: res.result.songs
		})
		//将搜索关键字添加到历史记录
		if (historyList.indexOf(searchContent) !== -1) {
			historyList.splice(historyList.indexOf(searchContent),1)
		}
		historyList.unshift(searchContent)
		this.setData({
			historyList
		})
		wx.setStorageSync('searchHistory',historyList)
	},
	
	handleClear() {
		this.setData({
			searchContent: '',
			searchList: []
		})
		
	},
	
	handleDelete() {
		let that = this
		wx.showModal({
			title:"删除记录",
			content: "确定删除记录？",
			success(res) {
				if (res.confirm) {
					that.setData({
						historyList: []
					})
					wx.removeStorageSync('searchHistory')
				}
			}
		})
		
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {

	}
})
